package com.example.skillcinema.ui.screens.main

import android.content.Context
import android.os.Bundle
import android.util.AttributeSet
import android.view.LayoutInflater
import android.view.View
import android.widget.LinearLayout
import androidx.navigation.findNavController
import com.example.skillcinema.adapters.FilmRecyclerViewAdapter
import com.example.skillcinema.databinding.FilmCollectionViewBinding
import com.example.skillcinema.db.displaymodels.FilmDisplayModel
import com.example.skillcinema.db.enums.FilmFetchType
import com.example.skillcinema.R
import com.example.skillcinema.db.repositories.BaseRepository.Companion.PREVIEW_ITEMS_COUNT
import com.example.skillcinema.ui.screens.main.FilmAllFragment.Companion.FILM_FETCH_TYPE_ARG
import com.example.skillcinema.utils.sharemodels.FilmDataToShare

class FilmCollectionView(context: Context, attrs: AttributeSet?) : LinearLayout(context, attrs) {
    private var _binding: FilmCollectionViewBinding? = FilmCollectionViewBinding.inflate(
        LayoutInflater.from(context), this, true
    )
    private val binding: FilmCollectionViewBinding
        get() = _binding!!
    lateinit var fetchedType: FilmFetchType
    private var filters: Pair<Int, Int>? = null
    override fun onDetachedFromWindow() {
        super.onDetachedFromWindow()
        _binding = null
    }

    private val filmAdapter: FilmRecyclerViewAdapter =
        FilmRecyclerViewAdapter({ id -> showFilmDetail(id) }, { showAllCollectionFilms() })

    init {
        binding.filmCollectionRecyclerView.adapter = filmAdapter
        binding.showAllButton.setOnClickListener {
            showAllCollectionFilms()
        }
    }

    fun setCollectionFilters(filt: Pair<Int, Int>) {
        filters = filt
    }

    fun setFilmFetchType(fetchType: FilmFetchType) {
        fetchedType = fetchType
    }

    fun setTitle(title: String) {
        binding.filmCollectionTitle.text = title
    }

    fun setData(films: List<FilmDisplayModel>) {
        filmAdapter.setData(films)
        if (films.count() >= PREVIEW_ITEMS_COUNT) {
            binding.showAllButton.visibility = VISIBLE
        }
    }

    private fun showFilmDetail(id: Int) {
        val bundle: Bundle = Bundle().apply {
            putInt(FilmDetailsFragment.FILM_ID_ARG, id)
        }
        findNavController().navigate(R.id.action_homeFragment_to_filmDetailsFragment, bundle)
    }

    private fun showAllCollectionFilms() {
        val bundle: Bundle = Bundle().apply {
            putParcelable(
                FILM_FETCH_TYPE_ARG,
                FilmDataToShare(
                    0,
                    fetchedType,
                    filters,
                    binding.filmCollectionTitle.text.toString()
                )
            )
        }
        findNavController().navigate(R.id.action_homeFragment_to_filmAllFragment, bundle)
    }
}